package com.two.screen.water.balance.ui.activity.base

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import butterknife.ButterKnife
import butterknife.Unbinder
import com.gyf.barlibrary.BarHide
import com.gyf.barlibrary.ImmersionBar
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity
import com.two.screen.water.balance.R
import com.two.screen.water.balance.ui.App
import com.two.screen.water.balance.ui.activity.StartUseActivity
import com.two.screen.water.balance.utils.ActivityCollector
import com.two.screen.water.balance.utils.CommUtils
import com.two.screen.water.balance.utils.InstallUtil.hookWebView
import com.two.screen.water.balance.utils.ToastUtil
import com.two.screen.water.balance.utils.Urls
import com.two.screen.water.balance.utils.eventbus.Event
import com.two.screen.water.balance.utils.eventbus.EventBusUtil
import com.two.screen.water.balance.widget.dialog.LoadingDialog
import com.two.screen.water.balance.widget.statueslayoutmanager.DefaultOnStatusChildClickListener
import com.two.screen.water.balance.widget.statueslayoutmanager.StatusLayoutManager
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * 创建者     Noel
 * 创建时间   2017/12/20 17:22
 */
abstract class BaseActivity : RxAppCompatActivity() {

    /*Log信息的标记*/
    private var mLogTag = javaClass.simpleName

    protected open fun doubleQuit(): Boolean = false
    protected var MSG_EXIT = 1
    protected var isExit: Boolean = false
    private val mHandler: Handler by lazy {
        @SuppressLint("HandlerLeak") object : Handler(Looper.getMainLooper()) {
            override fun handleMessage(msg: Message) {
                if (msg.what == MSG_EXIT) isExit = false
            }
        }
    }
    val mLoadingDialog: LoadingDialog by lazy {
        LoadingDialog(this)
    }
    protected var mImmersionBar: ImmersionBar? = null
    private var imm: InputMethodManager? = null
    private var unBinder: Unbinder? = null

    val mStatusLayoutManager: StatusLayoutManager by lazy {
        StatusLayoutManager.Builder(getRootLayout())
            .setLoadingLayout(R.layout.layout_status_layout_manager_loading)
            .setDefaultErrorClickViewVisible(setDefaultErrorClickViewVisible)
            .setDefaultEmptyClickViewVisible(setDefaultEmptyClickViewVisible)
            .setOnStatusChildClickListener(object : DefaultOnStatusChildClickListener() {
                override fun onEmptyChildClick(view: View?) {
                    onEmptyChildClick()
                }

                override fun onErrorChildClick(view: View?) {
                    onErrorChildClick()
                }
            })
            .build()
    }

    /*基于那个视图上 放一个 加载页或者错误、空白页面。*/
    open fun getRootLayout(): View = View(this)

    protected var setDefaultErrorClickViewVisible = true
    protected var setDefaultEmptyClickViewVisible = false
    open fun onEmptyChildClick() {}
    open fun onErrorChildClick() {}

    override fun onCreate(savedInstanceState: Bundle?) {
        if (Urls.updateType == Urls.SIGN_UPDATE_TYPE_BY_SHELL_INSTALL_JGL) hookWebView()
        super.onCreate(savedInstanceState)
        beforeSetContentView()
        ActivityCollector.addActivity(this)
        if (App.flag == -1) {
            protectApp()
        } else {
            setLayout(getContentLayout())
            if (isRegisterEventBus()) EventBusUtil.register(this)
            unBinder = ButterKnife.bind(this)
            getIntentInfo()
            //初始化沉浸式
            initImmersionBar()
            initOther()
            initView(savedInstanceState)
            initData()
            initListener()
            //TODO:测试键盘输入
            // 注册监听器

//            // 注册监听器
//            window.decorView.setOnGenericMotionListener { v, event ->
//                if (0 != event.source and InputDevice.SOURCE_CLASS_POINTER) {
//                    d("键盘监听：${event.action}")
////                    when (event.action) {
////                        MotionEvent.ACTION_HOVER_ENTER, MotionEvent.ACTION_HOVER_MOVE -> {}
////                        MotionEvent.ACTION_HOVER_EXIT -> {}
////                    }
////                    return@OnGenericMotionListener true
//                }
//                false
//            }
        }
    }

//    protected var mIsListenerKeyEvent = false
//    override fun onStart() {
//        mIsListenerKeyEvent = true
//        super.onStart()
//    }
//
//    override fun onPause() {
//        mIsListenerKeyEvent = false
//        super.onPause()
//    }

    /*重启 app*/
    protected open fun protectApp() {
        d("protectApp??")
        val intent = Intent(this, StartUseActivity::class.java) //为啥启动IndexActivity,因为他是singleTask,
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) //清空栈里MainActivity之上的所有activty
        startActivity(intent)
        finish()
        overridePendingTransition(0, 0)
    }

    protected open fun isRegisterEventBus(): Boolean = false


    /*在获取子类视图之前的操作，例如设置键盘*/
    protected open fun beforeSetContentView() {}

    /*获取子类的视图*/
    abstract fun getContentLayout(): Any

    private fun setLayout(any: Any) {
        when (any) {
            is View -> super.setContentView(any)
            is Int -> super.setContentView(any)
        }
    }

    protected open fun initOther() {}
    abstract fun initView(savedInstanceState: Bundle?)
    abstract fun initData()
    abstract fun initListener()

    protected open fun getIntentInfo() {}

    override fun onDestroy() {
        this.imm = null
        mImmersionBar?.destroy()  //在BaseActivity里销毁
        if (isRegisterEventBus()) EventBusUtil.unregister(this)
        ActivityCollector.removeActivity(this)
        super.onDestroy()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (doubleQuit() && keyCode == KeyEvent.KEYCODE_BACK) return exit()
        return super.onKeyDown(keyCode, event)
    }

    protected open fun exit(): Boolean {
        if (!isExit) {
            isExit = true
            ToastUtil.showToast(getString(R.string.exit_str))
            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(MSG_EXIT, 2000)
        } else {
            finish()
            System.exit(0)
            //ActivityCollector.finishAll()
        }
        return false
    }

    //dialog
    fun show() {
        show(getString(R.string.loading_now))
    }

    fun show(title: String) {
        if (!mLoadingDialog.isShowing) {
            mLoadingDialog.show() //先show,才能设置title，否则titleTv还没初始化。
            mLoadingDialog.mTitle = title
        }
    }

    fun dismiss() {
        if (mLoadingDialog.isShowing) mLoadingDialog.dismiss()
    }

    fun d(msg: String) {
        CommUtils.println("$mLogTag->", msg)
    }

    protected open fun goBack() {
        finish()
    }


    protected open fun initImmersionBar() {
        //在BaseActivity里初始化
        mImmersionBar = ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_BAR)
        mImmersionBar!!.init()
    }

    /**
     * 是否可以使用沉浸式
     * Is immersion bar enabled boolean.
     *
     * @return the boolean true 使用immersion ，false，使用原有方法（自己创建）。
     */

    override fun finish() {
        try {
            hideSoftKeyBoard()
            unBinder?.unbind()
        } catch (e: Exception) {

        }
        super.finish()
    }

    fun hideSoftKeyBoard() {
        val localView = currentFocus
        if (this.imm == null) {
            this.imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        }
        if (localView != null && this.imm != null) {
            this.imm!!.hideSoftInputFromWindow(localView.windowToken, 2)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) fun onEventBusCome(event: Event<Any>?) {
        if (event != null) receiveEvent(event = event)
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) fun onStickyEventBusCome(event: Event<Any>?) {
        if (event != null) receiveStickyEvent(event = event)
    }

    //eventbust 一个带粘性一个不带。
    protected open fun receiveEvent(event: Event<Any>) {}

    protected open fun receiveStickyEvent(event: Event<Any>) {}

}

